package com.sykj.seaflow.warm.module.design.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sykj.seaflow.warm.module.design.entity.SeaFlowDesign;
import com.sykj.seaflow.warm.module.design.params.*;
import com.sykj.seaflow.warm.module.design.service.SeaFlowDesignService;
import lombok.AllArgsConstructor;
import com.sykj.seaflow.common.base.bean.PageQuery;
import com.sykj.seaflow.common.base.bean.Result;
import com.sykj.seaflow.sys.remote.api.SysUserApi;
import com.sykj.seaflow.sys.remote.bean.SysUserBean;
import com.sykj.seaflow.warm.module.design.service.SeaFlowDesignService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 流程定义扩展信息
 */
@AllArgsConstructor
@RequestMapping("/flow/design")
@RestController
@Validated
public class SeaFlowDesignController {
    private final SeaFlowDesignService SeaFlowDesignService;
    private final SysUserApi sysuserApi;

    @PostMapping("/add")
    public void add(@Valid @RequestBody SeaFlowDesignAddParam addParam) {
        SeaFlowDesignService.add(addParam);
    }

    @PostMapping("/edit")
    public void edit(@RequestBody SeaFlowDesignEditParam editParam) {
        SeaFlowDesignService.edit(editParam);
    }
    @GetMapping("/page")
    public Result<SeaFlowDesign> page(SeaFlowDesignPageParam pageParam, PageQuery<SeaFlowDesign> pageQuery) {
        IPage<SeaFlowDesign> page = SeaFlowDesignService.page(pageParam, pageQuery);
        List<SeaFlowDesign> records = page.getRecords();
        List<Long> userIds = records.stream().map(SeaFlowDesign::getManagerId).collect(Collectors.toList());//.toList();
        if(ObjectUtil.isNotEmpty(userIds)){
            List<SysUserBean> users = sysuserApi.getUsers(userIds);
            records.forEach(record->{
                users.forEach(user->{
                    if(user.getId().equals(record.getManagerId())){
                        record.setManagerName(user.getNick());
                    }
                });
            });
        }
        return Result.build(page);
    }
    @PostMapping("/saveConfig")
    public Result<Void> saveConfig(@RequestBody SeaFlowDesignConfigParam configParam){
        SeaFlowDesignService.saveConfig(configParam);
        return Result.success("保存成功");
    }

    @GetMapping("/detail")
    public Result<SeaFlowDesign> detail(SeaFlowDesignIdParam idParam) {
        return Result.build(SeaFlowDesignService.get(idParam));
    }
    @PostMapping("/del")
    public Result<SeaFlowDesign> delete(@RequestBody List<SeaFlowDesignIdParam> idParam) {
        SeaFlowDesignService.del(idParam);
        return Result.build();
    }

    @PostMapping("/publish")
    public Result<String> publish(@RequestBody SeaFlowDesignIdParam idParam) {
        SeaFlowDesignService.publish(idParam);
        return Result.build();
    }
}
